<template>
  <div ref="chart1" style="width: 500px; height: 280px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'BarChart1',
  mounted() {
    this.initChart();
  },
  methods: {
    async initChart() {
      try {
        let res = await axios.get('http://localhost:7000/service-nepm/administrator/getProvinceMesg');
        let result = res.data.filter(item => item.PM_count > 0);
        result.sort((a, b) => b.PM_count - a.PM_count);

        let xAxisData = result.map(item => item.province_abbr);
        let seriesData = result.map(item => item.PM_count);

        let colorData = seriesData.map(() => getRandomColor());

        var chartDom = this.$refs.chart1;
        var myChart = echarts.init(chartDom);
        var option = {
          title: {
            text: '-- 悬浮颗粒物(PM2.5)浓度超标累计 --',
            left: 'center',
            textStyle: {
              color: '#fff'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            textStyle: {
              color: '#333'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              color: '#fff'
            }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              color: '#fff'
            },
            min: 0,
            minInterval: 1,
            boundaryGap: [0, '10%']
          },
          series: [{
            name: 'PM2.5超标数',
            type: 'bar',
            barWidth: '60%',
            data: seriesData.map((value, index) => ({
              value: value,
              itemStyle: {
                color: colorData[index]
              }
            }))
          }]
        };
        myChart.setOption(option);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }
  }
};

function getRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
</script>

<style scoped>
div {
  width: 100%;
  height: 100%;
}
</style>


